package org.six11.ss.server;

import java.io.PrintWriter;
import org.six11.ss.server.bean.Person;
import org.six11.ss.server.bean.Room;
import org.six11.ss.shared.Message;
import org.six11.util.adt.MultiState;
import org.six11.util.adt.SynchronizedQueue;

/**
 * This is a logic handler for logging users into the StellaSketch game system. 
 * 
 * @author Gabe Johnson <johnsogg@cmu.edu>
 */
public class LoginHandler extends AppletMessageHandler {

  /**
   * 
   * @param state
   */
  public LoginHandler(MultiState state) {
    super(state);
  }

  /**
   * Logs a user in. This establishes the various resources necessary for a player to do their
   * thing, including giving them a message queue, and putting them in the lobby.
   **/
  @Override
  public void handle(Message m, String sessionID, PrintWriter out) {
    int id = Integer.parseInt(m.getParam("personID"));
    Person person = loadPerson("" + id); // (Person) getSession().get(Person.class, id);
    if (person == null) {
      bug("Could not locate person " + id + " in the database.");
    } else {
      getSessionToPersonMap().put(sessionID, person.getId() + "");
      getPersonToMessageQueueMap().put(person.getId() + "", new SynchronizedQueue<Message>());
      RoomHandler rh = (RoomHandler) getHandler("room");
      Room lobby = (Room) getSession().get(Room.class, RoomHandler.ROOM_LOBBY);
      rh.joinRoom(lobby, person);
      // person.setRoom(lobby);
      bug("Found a person, gave them a queue and put them into the lobby.");
    }
  }

}
